/*
 * @Author: 18163104359 2205227953@qq.com
 * @Date: 2024-01-25 15:20:46
 * @LastEditors: NaturalHulk 2066634567@qq.com
 * @LastEditTime: 2024-02-23 18:11:06
 * @FilePath: /umi/src/pages/system/menu/form.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useEffect, forwardRef } from "react";
import { handleTree } from "@/utils/ruoyi.js";
import { Form, Select, TreeSelect, Input, Radio, Popover, InputNumber, Tree, Checkbox } from "antd";
import XHselectIcon from "@/components/xh-components/xh-select-icon";
import XHicon from "@/components/xh-components/xh-icon/index";
import { GetMenuListAPI } from "@/api/system/role.ts";
import "@/pages/system/role/index.less";
const { TextArea } = Input;
// 子组件forwardRef 防止时机不对找不到子组件的ref
const FormPage = forwardRef((props, ref) => {
  //展开指定的树节点
  const [expandedKeys, setExpandedKeys] = useState([]);

  //选中树结构的id集合数据
  const [checkedKeys, setCheckedKeys] = useState([]);

  //设置选中的树节点，多选需设置 multiple 为 true
  const [selectedKeys, setSelectedKeys] = useState([]);

  //是否自动展开父节点
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  //父子联动状态
  const [checkStrictly, setCheckStrictly] = useState(true);

  //菜单权限树结构数据
  const [menuList, setMenuList] = useState([]);

  //展开/收起节点时触发
  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  //选中树结构时
  const onCheck = (checkedKeys, checkInfo) => {
    if (checkStrictly) {
      formValue.setFieldsValue({
        ...data,
        menuId: checkedKeys.checked,
      });
      return setCheckedKeys(checkedKeys.checked);
    } else {
      formValue.setFieldsValue({
        ...data,
        menuId: checkedKeys,
      });
      return setCheckedKeys({ checked: checkedKeys, halfChecked: checkInfo.halfCheckedKeys });
    }
  };

  //递归
  const getAllDeptNode = (node) => {
    let keys = [];
    node.forEach((value) => {
      keys.push(value.key);
      if (value.children) {
        keys = keys.concat(getAllDeptNode(value.children));
      }
    });
    return keys;
  };
  const deptAllNodes = getAllDeptNode(menuList);

  //复选框选择时
  const onDeptOptionChange = (checkedValues) => {
    //展开/折叠
    if (checkedValues.includes("deptExpand")) {
      setExpandedKeys(checkedKeys);
    } else {
      setExpandedKeys(checkedKeys);
    }
    //全选/全不选
    if (checkedValues.includes("deptNodeAll")) {
      formValue.setFieldsValue({
        ...data,
        menuId: deptAllNodes,
      });
      setCheckedKeys(deptAllNodes);
    } else {
      formValue.setFieldsValue({
        ...data,
        menuId: deptAllNodes,
      });
      setCheckedKeys([]);
    }
    //父子联动
    if (checkedValues.includes("deptCheckStrictly")) {
      setCheckStrictly(false);
    } else {
      setCheckStrictly(true);
    }
  };

  const dataScopeOptions = [
    { value: "1", label: "全部数据权限" },
    { value: "2", label: "自定数据权限" },
    { value: "3", label: "本部门数据权限" },
    { value: "4", label: "本部门及以下数据权限" },
    { value: "5", label: "仅本人数据权限" },
  ];

  const { data = { dataScope: "1" }, title } = props;
  // 表单数据
  const [formValue] = Form.useForm();
  // 监听表单数据变化 useWatch

  // 初始化数据
  const initData = () => {
    formValue.setFieldsValue(data);
    setCheckedKeys(data.menuIds);
  };

  // 获取菜单数据
  const getmenuList = async () => {
    const result = await GetMenuListAPI({ type: 1 });
    setMenuList(handleTree(result.data, "menuId"));
  };

  const [dataScopeId, setDataScopeId] = useState("");
  const onChangeSelect = (val) => {
    // setDataScopeId(val);
    formValue.setFieldsValue({ ...data, dataScope: val });
  };

  useEffect(() => {
    initData();
    getmenuList();
  }, []);

  return (
    <Form
      form={formValue}
      ref={ref}
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 10,
      }}
      initialValues={{
        remember: true,
      }}
      autoComplete="off"
    >
      <Form.Item
        disabled={title == "查看"}
        label="角色名称"
        name="roleName"
        rules={[
          {
            required: true,
            message: "请填写角色名称",
          },
        ]}
      >
        <Input placeholder="请填写角色名称" />
      </Form.Item>
      {title == "数据权限" ? (
        <>
          <Form.Item
            label="权限范围"
            name="dataScope"
            rules={[
              {
                required: true,
                message: "请选择权限范围",
              },
            ]}
          >
            <Select
              allowClear
              // mode="multiple"
              style={{
                width: "100%",
              }}
              onChange={onChangeSelect}
              placeholder="请选择权限范围"
              options={dataScopeOptions}
            />
          </Form.Item>
        </>
      ) : (
        ""
      )}

      {/* <Form.Item
        disabled={title == "查看"}
        label="权限字符"
        name="roleKey"
        rules={[
          {
            required: true,
            message: "请填写权限字符",
          },
        ]}
      >
        <Input placeholder="请填写权限字符" />
      </Form.Item> */}

      {title != "数据权限" ? (
        <>
          <Form.Item
            label="显示排序"
            name="roleSort"
            rules={[
              {
                required: true,
                message: "请填写显示排序",
              },
            ]}
          >
            <InputNumber />
          </Form.Item>
        </>
      ) : (
        ""
      )}

      {title != "数据权限" || data.dataScope == "2" ? (
        <>
          <Form.Item
            disabled={title == "查看"}
            label="菜单权限"
            name="menuId"
            wrapperCol={{ span: 12 }}
          >
            <div>
              <Checkbox.Group
                options={[
                  { label: "展开/折叠", value: "deptExpand" },
                  { label: "全选/全不选", value: "deptNodeAll" },
                  { label: "父子联动", value: "deptCheckStrictly" },
                ]}
                onChange={onDeptOptionChange}
              />
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8 }}>
            <div className="treeClass">
              <Tree
                checkable
                onExpand={onExpand}
                fieldNames={{ title: "menuName", key: "menuId", children: "children" }}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                checkStrictly={checkStrictly}
                treeData={menuList}
              />
            </div>
          </Form.Item>
        </>
      ) : (
        ""
      )}

      {title != "数据权限" ? (
        <>
          <Form.Item disabled={title == "查看"} label="角色描述" name="roleDescription">
            <TextArea rows={4} placeholder="请输入角色描述" maxLength={6} />
          </Form.Item>
        </>
      ) : (
        ""
      )}
    </Form>
  );
});
export default FormPage;
